<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class vProduct extends Controller {

    /**
     * 商品列表显示数量
     */
    const LIST_LIMIT = 10;

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * Product Detail
     * @param type $Query
     */
    public function view($Query) {
        // 推荐com，90分钟
        if ($this->pCookie('com') && isset($Query->com)) {
            $this->sCookie('com', 5400);
        }

        if (isset($Query->com)) {
            // spread++
            $spreadUpdateSql = "UPDATE " . COMPANY_SPREAD . " SET `readi` = `readi` + 1 WHERE `product_id` = $Query->id AND `com_id` = '$Query->com';";
            $this->Db->query($spreadUpdateSql);
        }

        // $openid = $this->getOpenId();

        $Query->id = intval($Query->id);
        $this->cacheId = $Query->id;

        if (!$this->isCached($Query->id)) {
            $this->loadModel('Product');
            // productinfo
            $productInfo = $this->Db->getOneRow(sprintf("SELECT * FROM `vproductinfo` WHERE product_id = %s;", $Query->id));
            // 产品图片
            $images = $this->Db->query("SELECT * FROM `product_images` WHERE `product_id` = $Query->id;");
            $productInfo['images'] = $images;
            $productInfo2 = $this->Db->getOneRow(sprintf("SELECT * FROM `products_info` WHERE product_id = %s;", $Query->id));
            // 加入产品首图到图片列表
            $images[] = array('image_path' => $productInfo2['catimg']);
            $image_count = count($images);
            // 计算首图高度
            if ($image_count === 1) {
                if (@$image_size = getimagesize(dirname(__FILE__) . '/../static/product_hpic/' . $productInfo2['catimg'])) {
                    $this->Smarty->assign('catimage_height', $image_size[1]);
                } else {
                    // gd失效或者无法获取
                    $this->Smarty->assign('catimage_height', false);
                }
            }
            // 随机product推荐
            $sList = $this->Product->randomGetProducts($productInfo2['product_cat'], $Query->id, 3);
            $this->Smarty->assign('slist', $sList);
            $this->Smarty->assign('shareimg', $this->root . 'static/product_hpic/' . $productInfo['catimg']);
            $this->Smarty->assign('images', $images);
            $this->Smarty->assign('productInfo', $productInfo);
            $this->Smarty->assign('productInfo2', $productInfo2);
            $this->Smarty->assign('productid', $Query->id);
            // $this->Smarty->assign('comid', $openid);
            $this->Smarty->assign('title', $productInfo['product_name']);
        }

        // readi
        $this->Db->query("UPDATE `products_info` SET `product_readi` = `product_readi` + 1 WHERE `product_id` = $Query->id;");

        $this->show();
    }

    /**
     * 查看产品分类介绍
     * @param type $Query
     */
    public final function view_category($Query) {
        !isset($Query->cat) && $Query->cat = 0;

        $this->cacheId = $Query->cat;

        // 缓存
        if (!$this->isCached()) {
            $this->loadModel('Product');
            $topCats = $this->Product->getCatList(0);
            $catInfo = $this->Product->getCatInfo($Query->cat);
            $subCatInfo = $this->Product->getCatList($catInfo['cat_id']);
            $this->Smarty->assign('topcat', $topCats);
            $this->Smarty->assign('subcat', $subCatInfo);
            $this->Smarty->assign('title', '产品搜索');
            $this->Smarty->assign('cat', $Query->cat);
            $this->Smarty->assign('serial_id', $Query->serial_id);
            $this->Smarty->assign('cat_descs', $catInfo['cat_descs']);
        }

        $this->show();
    }

    /**
     * ajax获取分类列表视图
     * @param type $Query
     */
    public final function ajaxCatList($Query) {
        if (isset($Query->id)) {
            $this->loadModel('Product');
            $subCatInfo = $this->Product->getCatList($Query->id);
            foreach ($subCatInfo as &$s) {
                $childrens = $this->Product->getCatList($s['cat_id']);
                if (count($childrens) > 0) {
                    $s['child'] = $childrens;
                } else {
                    $s['child'] = false;
                }
            }
            $this->cacheId = $Query->id;
            $this->Smarty->assign('subcat', $subCatInfo);
            $this->show();
        }
    }

    /**
     * 商品列表
     * @param type $Query
     */
    public function view_list($Query) {
        $this->getOpenId();

        !isset($Query->page) && $Query->page = 0;
        !isset($Query->searchkey) && $Query->searchkey = '';
        !isset($Query->serial) && $Query->serial = false;
        !isset($Query->cat) && $Query->cat = 1;
        !isset($Query->orderby) && $Query->orderby = "";
        $Query->searchkey = urldecode($Query->searchkey);

        $this->cacheId = md5(serialize($Query));

        // 推荐com，90分钟
        if (!isset($this->pGet['com']) && isset($Query->com)) {
            setcookie("com", $Query->com, time() + 5400);
        }

        if (!$this->isCached()) {
            $this->loadModel('Product');
            // params
            if ($Query->searchkey != '') {
                $catInfo = array(
                    'cat_id' => $Query->cat,
                    'cat_name' => $Query->searchkey
                );
            } else if ($Query->serial) {
                $serialInfo = $this->Product->getSerialInfo($Query->serial);
                $catInfo = array(
                    'cat_name' => $serialInfo['serial_name']
                );
            } else {
                $catInfo = $this->Product->getCatInfo($Query->cat);
            }

            $this->Smarty->assign('serial', $Query->serial);
            $this->Smarty->assign('query', $Query);
            $this->Smarty->assign('searchkey', $Query->searchkey);
            $this->Smarty->assign('cat', $Query->cat);
            $this->Smarty->assign('catInfo', $catInfo);
            $this->Smarty->assign('orderby', $Query->orderby);
            $this->Smarty->assign('title', $catInfo['cat_name']);
        }

        $this->show();
    }

    /**
     * Ajax返回商品列表 分页
     * @todo cat
     * @param type $Query
     */
    public function ajaxProductList($Query) {
        // 商品系列
        !isset($Query->serial) && $Query->serial = false;
        // 分页号
        !isset($Query->page) && $Query->page = 0;
        // 排序
        if (!isset($Query->orderby) || $Query->orderby == "") {
            $Query->orderby = '`sort` DESC';
        } else {
            $Query->orderby = trim(urldecode($Query->orderby));
        }
        // 商品分类
        !isset($Query->cat) && $Query->cat = 1;
        // 缓存id
        $this->cacheId = md5(serialize($Query));
        // 列表宫格样式标记
        $this->Smarty->assign('stype', $Query->stype);

        if (!$this->isCached()) {
            $this->loadModel('Product');
            if ($Query->page != 0) {
                $pdlists1 = $this->pCookie('pdlist-serial');
                $pdlists2 = $this->pCookie('pdlist-start');
            } else {
                $pdlists1 = false;
                $pdlists2 = 0;
            }
            $serials = $this->Product->getSerials($pdlists1);
            $limit = 10;
            // Query limit statment
            $queryLimit = $Query->page * $limit . "," . $limit;
            // search key
            if ((isset($Query->searchKey) && $Query->searchKey != '') || $Query->serial) {
                // 系列展示列表
                if (is_numeric($Query->serial)) {
                    $categorys = array();

                    $LIMIT = "";
                    $WHERE = "`delete` <> 1 AND `product_serial` = " . $Query->serial;
                    $_SQL = sprintf("SELECT po.*,ps.sale_prices,psl.serial_name,pca.cat_name "
                            . "FROM `products_info` po "
                            . "LEFT JOIN `product_onsale` ps ON po.product_id = ps.product_id "
                            . "LEFT JOIN `product_serials` psl ON psl.id = po.product_serial "
                            . "LEFT JOIN `product_category` pca ON pca.cat_id = po.product_cat "
                            . "WHERE $WHERE ORDER BY `cat_order` DESC LIMIT $pdlists2,1000;");

                    $pds = $this->Db->query($_SQL);

                    foreach ($pds as $pd) {
                        if (!array_key_exists($pd['product_cat'], $categorys)) {
                            $categorys[$pd['product_cat']] = array();
                            $categorys[$pd['product_cat']]['cat_name'] = $pd['cat_name'];
                            $categorys[$pd['product_cat']]['pd'] = array();
                        }
                        $categorys[$pd['product_cat']]['pd'][] = $pd;
                    }

                    $pdLoaded = count($pds);
                    $this->sCookie('pdlist-start', $pdlists2 + $pdLoaded);
                    $this->Smarty->assign('pdloaded', $pdLoaded);
                    $this->Smarty->assign('categorys', $categorys);
                } else {
                    $Query->searchKey = urldecode($Query->searchKey);
                    $_SQL = sprintf("SELECT * FROM `products_info` WHERE `product_name` LIKE '%%$Query->searchKey%%' AND `delete` = 0 ORDER BY %s LIMIT %s;", $Query->orderby, $queryLimit);
                }
                $this->show('vproduct/ajaxproductlist_serials.tpl');
            } else {
                // 搜索展示列表
                $pdLoaded = 0;
                $serialsCount = count($serials) - 1;
                foreach ($serials as $index => &$seri) {
                    $seri['s'] = $index == 0 && $Query->page != 0;
                    $WHERE = "`product_cat` = $Query->cat AND `delete` <> 1 AND `product_serial` = " . $seri['id'];
                    $_SQL = sprintf("SELECT po.*,ps.sale_prices,psl.serial_name "
                            . "FROM `products_info` po "
                            . "LEFT JOIN `product_onsale` ps ON po.product_id = ps.product_id "
                            . "LEFT JOIN `product_serials` psl ON psl.id = po.product_serial "
                            . "WHERE $WHERE ORDER BY %s LIMIT %s;", $Query->orderby, "$pdlists2," . $limit);
                    $seri['pd'] = $this->Db->query($_SQL);
                    $seri['pdCount'] = count($seri['pd']);
                    $pdLoaded += $seri['pdCount'];
                    $limit -= $seri['pdCount'];
                    if ($limit <= 0 || $index == $serialsCount) {
                        $this->sCookie('pdlist-serial', $seri['sort']);
                        if ($seri['sort'] == $pdlists1) {
                            $this->sCookie('pdlist-start', $pdlists2 + $seri['pdCount']);
                        } else {
                            $this->sCookie('pdlist-start', $seri['pdCount']);
                        }
                        $serials = array_slice($serials, 0, $index + 1);
                        break;
                    }
                    $pdlists2 = 0;
                }
                // echo $pdLoaded;
                $this->Smarty->assign('pdloaded', $pdLoaded);
            }
            $this->Smarty->assign('serials', $serials);
            // vproduct/ajaxproductlist.tpl
            $this->show();
        }
    }

    /**
     * Cart data
     * @return HTML STRING
     */
    public function cartData() {
        $data = json_decode($_POST['data'], true);
        $_tmp = array();
        foreach ($data as $key => $product) {
            array_push($_tmp, $key);
        }
        $_SQL = sprintf("SELECT * FROM `vproductinfo` WHERE `product_id` IN (%s);", implode(',', $_tmp));
        $this->Smarty->assign('product_list', $this->Db->query($_SQL));
        $this->Smarty->assign('product_data', $data);
        $this->show();
    }

    /**
     * 上传产品图片
     * ImageUpload
     */
    public function ImageUpload($Query) {
        if (!empty($_FILES)) {
            $dirname = dirname(__FILE__) . "/../static/product_hpic2/";
            $tempFile = $_FILES['jUploaderFile']['tmp_name'];
            $targetPath = $dirname;
            $targetFileName = md5($_COOKIE['_uid'] . time()) . '.' . strtolower(end(explode('.', $_FILES['jUploaderFile']['name'])));
            $targetFile = str_replace('//', '/', $targetPath) . $targetFileName;

            $state = move_uploaded_file($tempFile, $targetFile) ? 1 : 0;
            chmod($targetFile, 0777);

            if ($state == 1) {
                if (@$dims = getimagesize($targetFile)) {
                    $imginfo = array(
                        "width" => $dims[0],
                        "height" => $dims[1]
                    );
                } else
                    $imginfo = null;
            }
        } else {
            $state = 0;
        }
        $arr = array(
            "s" => $state,
            "pic" => $dirname . $targetFileName,
            "imgn" => $targetFileName,
            "size" => $imginfo
        );

        $json = json_encode($arr);
        print_r($json);
    }

    /**
     * 
     * @param type $Query
     */
    public function ajaxGetCategroys() {
        $this->loadModel('SqlCached');
        // file cached
        $cacheKey = 'ajaxGetCategroys';
        $fileCache = new SqlCached();
        $ret = $fileCache->get($cacheKey);
        if (-1 === $ret) {
            $this->loadModel('Product');
            $cats = $this->toJson($this->Product->getAllCats());
            $fileCache->set($cacheKey, $cats);
            echo $this->unIescape($cats);
        } else {
            echo $this->unIescape($ret);
        }
    }

    /**
     * 
     * @param type $catname
     * @param type $pid
     */
    public function ajaxAddCategroy() {
        $catname = trim($this->post('catname'));
        $pid = intval($this->post('pid'));
        echo $this->Db->query("INSERT INTO `product_category` (cat_name,cat_parent) VALUES ('$catname',$pid);");
    }

    /**
     * 
     * @param type $catname
     * @param type $pid
     */
    public function ajaxDelCategroy() {
        $id = $this->post('id');
        echo $this->Db->query("DELETE FROM `product_category` WHERE cat_id = $id;");
    }

    /**
     * alter
     */
    public function ajaxAlterCategroy() {
        $catid = intval($this->post('catid'));
        $catname = trim($this->post('catname'));
        $catimage = $this->post('catimage');
        $catdesc = $this->post('catdesc');
        #echo "UPDATE `product_category` SET cat_name = '$catname',cat_image = '$catimage',cat_descs = '$catdesc' WHERE cat_id = $catid;";
        echo $this->Db->query("UPDATE `product_category` SET cat_name = '$catname',cat_image = '$catimage',cat_descs = '$catdesc' WHERE cat_id = $catid;");
    }

}
